package com.java2007.service.impl;


import com.java2007.entity.CartItem;
import com.java2007.factory.BeanFactory;
import com.java2007.pojo.Food;
import com.java2007.service.CartService;
import com.java2007.service.FoodService;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;
/**
 * 餐车业务层
 */
public class CartServiceImpl implements CartService {
    private FoodService foodService= (FoodService) BeanFactory.getBean("com.java2007.service.impl.FoodServiceImpl");
    /**
     *
     * @param foodId 菜品id
     * @param num 菜品数量
     * @param list 餐车集合
     * @return
     */
    @Override
    public List<CartItem> add(int foodId, int num, List<CartItem> list) throws SQLException {
        for (CartItem cartItem:list) {
            //餐车存在菜品信息，进行修改
            if (cartItem.getFoodId()==foodId){
                cartItem.setNum(cartItem.getNum()+num);
                if (cartItem.getNum()<=0){
                    list.remove(cartItem);
                }
                cartItem.setTotalPrice(cartItem.getFoodPrice()*cartItem.getNum());
                cartItem.setUpdateTime(new Date());
                return list;
            }
        }

        //根据foodId查询出food对象
        Food food = foodService.findByFoodId(foodId);
        //餐车不存在菜品信息，新建并储存信息
        CartItem cartItem=new CartItem();
        cartItem.setFoodId(foodId);
        cartItem.setFoodName(food.getFoodName());
        cartItem.setFoodPrice(food.getPrice());
        cartItem.setNum(num);
        cartItem.setTotalPrice(cartItem.getNum()*cartItem.getFoodPrice());
        cartItem.setCreateTime(new Date());
        cartItem.setUpdateTime(new Date());
        //将菜品信息放进餐车集合
        list.add(cartItem);
        return list;
    }

}
